package io.geekidea.boot.util.api;

import com.alibaba.fastjson2.JSONObject;
import io.geekidea.boot.common.constant.JieAnBoAPiConstant;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * 捷安宝接口调用工具类
 * 目前仅作为标识类，实际业务逻辑可能在其他地方实现
 *
 * @author geekidea
 * @date 2023/11/26
 **/
@Slf4j
@Data
@Component
public class JieAnBoApi {

    private static final RestTemplate restTemplate = new RestTemplate();

    public static String sign(String biz_content) {
        String signTemp = "app_id=" + JieAnBoAPiConstant.APP_ID + "&biz_content=" + biz_content + "&timestamp="
                + System.currentTimeMillis() + "&app_secret=" + JieAnBoAPiConstant.APP_SECRET;
        return DigestUtils.md5Hex(signTemp).toUpperCase();
    }

    // 通用POST
    public static JSONObject postForJson(String url, String bizContent) {
        // 组装完整请求体
        String requestBody = String.format(
                "{\"app_id\":\"%s\",\"biz_content\":%s,\"sign\":\"%s\",\"timestamp\":\"%s\"}",
                JieAnBoAPiConstant.APP_ID, bizContent, sign(bizContent), String.valueOf(System.currentTimeMillis()));

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

        try {
            String respStr = restTemplate.postForObject(url, entity, String.class);
            return JSONObject.parseObject(respStr);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
